<template>
<!-- 数据准备新增、维护页面 -->
  <div class="group">
      <div class="addBox">
        <i  @click="showAddBox('OneTitle')"  class="el-icon-circle-plus">新增一级分组</i>
        <i @click="compile" class="el-icon-edit">编辑</i>
      </div>
      <el-tree
                     ref="tree"
                     :highlight-current="true"
                     :data="menuData"
                     node-key="menuId"
                     :expand-on-click-node="false">
        <span style="ligin-height:40px;" @click="showTable(data)" class="custom-tree-node" slot-scope="{ node, data }" @mouseenter="mouseenter(data)" @mouseleave="mouseleave(data)">
          <li  :class="{'activeBGC':(data.menuId==activatedId && !isOne),'el-icon-folder-opened':data.attr=='1'}">
            <span style="margin-right:10px;font-size:12px;color:#ccc">{{getLabel(data.type)}}</span>{{data.name}}
          </li>
            <span style="margin-left: 20%">
                <el-button class="tree-btn el-icon-folder-add" v-show="data.attr=='1' && data.show" type="text" @click="showAddBox(node, data)"></el-button>
                <el-button class="tree-btn el-icon-edit" v-show="data.show" type="text" @click="rename(node, data,menuId)"  ></el-button>
                <el-button class="tree-btn el-icon-delete" v-show="data.show" type="text" @click="remove(node, data,menuId)"></el-button>
            </span>
        </span>
            </el-tree>
      <el-dialog title="重命名" :visible.sync="isShowReNam" width="40%" :before-close="closeBox">
        <div  v-if="isShowReNam" class="addModel">
          <div class="selectType">
              <el-form label-position="right" label-width="100px">
                  <el-form-item label="原名称">{{renameData.name}}</el-form-item>
                  <el-form-item label="修改名称">
                      <el-input size="mini" style='width:60%' v-model="reNameVal"></el-input>
                  </el-form-item>
              </el-form>
          </div>
        </div>
          <span slot="footer" class="dialog-footer">
               <el-button size="mini" type="primary" @click="updateName">修改</el-button>
            <el-button size="mini" type="primary" @click="closeBox">取消</el-button>
          </span>
      </el-dialog>
      <el-dialog title="新增表/分组" :visible.sync="isShowAddModel" width="40%" :before-close="closeBox">
        <div v-if="isShowAddModel" class="addModel">
          <div style="width:100%;margin:20px 65px;">
            <el-radio v-model="radio" label="1" border size="mini">新增分组</el-radio>
            <el-radio v-model="radio" label="2" border size="mini">新增表</el-radio>
          </div>
            <div class="selectType">
                <el-form label-position="right" label-width="100px">
                    <el-form-item label="上级名称">
                        <span v-if="!isOne" style="ligin-heiht:60px;margin-left:14px">{{makedate.name?makedate.name : '新增一级分组'}}</span>
                    </el-form-item>
                    <el-form-item label="新增表类型" v-show="radio==2">
                        <el-select size="mini" v-show="radio==2" v-model="tableTitle" @change="goPage(tableTitle)" filterable placeholder="请选择" style="width: 80%">
                            <el-option
                                v-for="item in options"
                                :key="item.tableTitle"
                                :label="item.label"
                                :value="item.tableTitle">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="表/分组名称">
                        <el-input v-model="newTitle" placeholder="请输入..." size="mini" style="width: 80%"></el-input>
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input size="mini"
                                  style="width: 80%"
                                  type="textarea"
                                  :rows="2"
                                  placeholder="请输入备注"
                                  v-model="textarea">
                        </el-input>
                    </el-form-item>
                </el-form>
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
              <el-button type="primary" size="mini" @click="addMenuData">保存</el-button>
              <el-button type="primary" size="mini" @click="cancel">取消</el-button>
          </span>
        </el-dialog>
  </div>
</template>
<script>
import {MGNDIRQUERY1, TMGNDIRMAINTAIN} from '@api/url'
import getTime from '@/assets/js/getDate'
export default {
   data () {
      return {
        tag: '',
        selectMenuData: {}, // 选中的表，作为编辑跳转用
        reNameVal: '', // 修改后的表或者分组名称
        isOne: false, // 是否增加一级标题 默认不是
        textarea: '', // 添加分组时备注
        makedate: {}, // 操作数据
        menuId: '1',
        activeColor: false,
        newId: 1, // 前端生成id
        tableTitle: '',
        newTitle: '', // 新增表名称
        radio: '2', // 2新增表  1新增分组
        renameData: {name: ''},
        isShowReNam: false, // 重命名框是否显示
        isShowAddModel: false, // 添加表名是否显示
        menuData: [],
        defaultShow: null,
        // 11-sql,12-EXCEL,13-数据库表，14-自助数据集,2-目录，3-菜单，4-数据连接，5-外部连接
        options: [
          {
          tableTitle: '11',
          label: 'SQL'
          }, {
            tableTitle: '12',
            label: 'EXCEL'
          }, {
            tableTitle: '13', // attr:1-分组，目录，2-叶子节点，表名，子菜单 11-sql,12-EXCEL,13-数据库表，14-自助数据集
            label: '数据库表'
          }, {
          tableTitle: '14',
          label: '自助数据集'
        }],
        arr1: [
          {
            tableTitle: '4',
            label: 'IN'
          },
          {
            tableTitle: '5',
            label: 'OUT'
          },
          {
          tableTitle: '11',
          label: 'SQL'
          }, {
            tableTitle: '12',
            label: 'EX'
          }, {
            tableTitle: '13', // attr:1-分组，目录，2-叶子节点，表名，子菜单 11-sql,12-EXCEL,13-数据库表，14-自助数据集
            label: 'DB'
          }, {
          tableTitle: '14',
          label: 'SE'
        }],
        tableTitle: '',
        activatedId: ''
      }
    },
    created () {
       this.getTree()// 查询目录
    },
   methods: {
     // 通过传入key值返回名称
     getLabel (key) {
       let label = ''
       this.arr1.forEach(ele => {
         if (ele.tableTitle == key) {
           console.log(ele.label)
            label = ele.label
         }
       })
       return label
     },
     // 跳转
     compile () {
         debugger
       this.activeColor = 'true'
       if (this.selectMenuData.menuId) {
         this.$storeSave.state.updateObj = this.selectMenuData
         // this.$storeSave.state.addelevanceObj={};//新增数据清空
           console.log(this.$storeSave.state.addelevanceObj)
         this.$storeSave.state.mainTableData = {}// 已选主表对象为空
         this.$emit('select-table', this.selectMenuData, 'update')
       } else {
         this.$alert('请先选择修改的目录', '提示', {
            confirmButtonText: '确定',
            callback: action => {

            }
          })
       }
     },
     // 显示增加表格数据的盒子
      showAddBox (node, data) {
        this.isShowAddModel = true
        console.log('选中按钮')
        console.log(this.radio)
        console.log(node)
        // 如果是通过点击新增一级标题来的,操作数据为空对象
        if (node == 'OneTitle') {
          this.isOne = true
          this.radio = '1'
          this.makedate = {}
        } else {
          this.activatedId = data.menuId
          console.log(`id:${this.activatedId}`)
           this.makedate = data
           this.isOne = false // 是否为一级菜单
           console.log(data)
        }
      },
      // 修改表名
      updateName () {
        if (!this.reNameVal) {
          this.$alert('当前无任何修改项，请输入修改的信息', {
              type: 'error',
              confirmButtonText: '确定'
          })
        } else {
          this.isShowReNam = false// 关闭修改框
          this.renameData.name = ''
          this.updateModel()
        }
      },
      goPage (type) {
        console.log(type)
        this.$emit('select-type', type)
      },
      cancel () {
        this.isShowAddModel = false
      },
      showTable (data) {
        console.log('显示右侧表格数据')
        console.log(data)
        if (data.attr != '1') {
           // 选择了操作的元数据表主表---用于数据准备
          this.$storeSave.state.selectMenuData = data
          this.selectMenuData = data
          this.$emit('select-table', data, 'query') // 调用查询数据预览
          this.activatedId = data.menuId
        }
        console.log(`id:${this.activatedId}`)
      },
      // 重命名
      rename (node, data) {
        this.isOne = false
        this.isShowReNam = true
        this.renameData = data
        this.activatedId = data.menuId
        console.log(`id:${this.activatedId}`)
      },
      addEvent (param, obj) {
        debugger
        this.$http.post(TMGNDIRMAINTAIN, param).then(res => {
          console.log('新建表新增成功')
          console.log(res)
         if (res.data.code == '200') {
           this.tableTitle = ''
           this.textarea = ''
           this.makedate = {}
           this.newTitle = ''
           this.$storeSave.state.mainTableData = {}// 已选主表对象为空
           this.$storeSave.state.updateObj = {}// 编辑字段置空
           this.$storeSave.state.selectMenuData = {}// 已选字段
           this.isShowAddModel = !this.isShowAddModel
           if (this.radio == '2') { // 表
            this.$storeSave.state.addelevanceObj = res.data.data
          }
           this.getTree()
           if (obj && this.radio == '2') {
             // obj新增好的元素
             this.$emit('select-table', obj, 'add')
           }
         } else {
           this.$alert(res.data.message || '失败', '提示', {
            confirmButtonText: '确定',
            callback: action => {

            }
           })
         }
        }).catch(err => {
          console.log('新建表新增失败')
          console.log(err)
          this.$alert(err.data.message, '提示', {
            confirmButtonText: '确定',
            callback: action => {

            }
           })
        })
      },
      addMenuData (param) {
        // 非空判断
        // 新增表的时候，新增类型不能为空 名称不能为空
        // 新增分组的时候 名称不能为空
        //  radio: '2',//2新增表  1新增分组
        //   if (this.radio === '1') {
        //       // if (!this.tableTitle) {
        //       //     // 新增类型不能为空
        //       //     this.$message({
        //       //         // type: 'error',
        //       //         message: '表/分组名称不能为空！'
        //       //     });
        //       //     return
        //       // }
        //       var condition = {
        //           radio: this.radio,
        //           newTitle: this.newTitle
        //     }
        //       this.$http.post(TMGNDIRMAINTAIN, condition).then(res=> {
        //           this.$storeSave.state.addelevanceObj=res.data.data
        //       }).catch(err=> {
        //           console.log('新建表新增失败')
        //       })
        //   }
        //   this.isShowAddModel= this.isShowAddModel
        if (this.radio == '2') {
          if (!this.tableTitle) {
            // 新增类型不能为空
              this.$message({
                  type: 'error',
                  message: '新增类型不能为空,请选择新增类型！'
              })
              return
          }
        }
        if (!this.newTitle) {
            this.$message({
                type: 'error',
                message: '表/分组名称不能为空,请选择新增类型！'
            })
            return
          }
        // console.log(this.makedate)//父级数据
        let timeStr = getTime.getTime()
        this.newId++
        let menuId = `${timeStr}${this.newId}`
        const newChild = {
          optMode: 'A', // A代表新增
          menuId: menuId, // id
          name: this.newTitle, // 表格名称
          parentId: this.isOne ? '0' : this.makedate.menuId,
          type: this.tableTitle || '1', // 新增类型  //  11-sql,12-EXCEL,13-数据库表，14-自助数据集,2-目录，3-菜单，4-数据连接，5-外部连接
          attr: this.radio, // 子节点还是分组
          path: '', // 路径
          seqno: '1', // 排最前面
          mark: this.textarea, // 描述
          createdBy: this.$storeSave.state.userInfo.username || 'XXX', // 创建人登陆用户名
          createdDt: timeStr// 创建时间
          }
        // this.addelevanceId
        this.$storeSave.state.updateObj = {}// 编辑对象置空
        this.$storeSave.state.selectMenuData = {}// 选择字段为空
        if (newChild.attr == '2') {
                // 表
            this.$storeSave.state.newChild = newChild
            console.log('this.$storeSave.state.newChild')
            console.log(this.$storeSave.state.newChild)
            debugger
            // 清除数据
            let param = {makeData: this.makedate, tableTitle: '自助数据集'}
            this.$emit('select-table', param, 'add') // 跳转
            this.tableTitle = ''
            this.textarea = ''
            this.makedate = {}
            this.newTitle = ''
            this.$storeSave.state.mainTableData = {}// 已选主表对象为空
            this.$storeSave.state.updateObj = {}// 编辑字段置空
            this.$storeSave.state.selectMenuData = {}// 已选字段
            this.isShowAddModel = !this.isShowAddModel
            this.getTree()// 查询目录
            return
          }
        // 存储新建立的数据集合数据
        if (newChild.parentId == '0') {
            this.$alert('您是否确认增加一级分类', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              this.addEvent(newChild)
            }
          })
        } else {
          console.log(this.tableTitle)
        }
      },
      // MGNDIRQUERY  查询目录
      getTree () {
        let param = {
          parentId: '0',
          menuId: '0', // 0查询全树，否则查询该节点下树
          type: '1', // 1-数据集，2-目录，3-菜单，4-数据连接，5-外部连接
          optMode: '1'
        }

         this.$http.post(MGNDIRQUERY1, param).then(res => {
           console.log(res.status)
           console.log('==========================')
           console.log(res.data.data)
           if (res.status == '200') {
            this.menuData = res.data.data
            this.isHaveChildren(this.menuData)
            console.log(res.data.data)
               this.getTheDefaultShow()
           }
         })
         this.menuData = []
      },
      isHaveChildren (data) {
        data.forEach(element => {
          console.log('DDDDDDDDDDDDDDDDDDDDDDDDDDDDDD')
          element.label = this.getLabel(element.type)
          if (element.children.length > 0) {
            console.log('CCCCCCCCCCCCCCCCCCCCCCC')
            this.isHaveChildren(element.children)
          }
        })
      },
      // 删除树节点
      deleteModel (menuId) {
        this.isOne = false
        let param = {
          menuId: menuId,
          'optMode': 'D'
          }
        this.$http.post(TMGNDIRMAINTAIN, param).then(res => {
          console.log('删除成功')
          console.log(res)
          if (res.data.code == '200') {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getTree()
          }
        }).catch(err => {
          console.log('删除菜单失败')
          console.log(err)
        })
      }, // 删除树节点
      updateModel () {
        // this.renameData
        console.log(this.renameData)
        console.log('this.this.this.this.this.this.renameData')
        let param = {
          optMode: 'U', // 定值
          menuId: this.renameData.menuId, // 菜单id
          name: this.reNameVal, // 重命名名称
          type: this.renameData.type, // 类型
          attr: this.renameData.attr,
          parentId: this.renameData.parentId, // 父级id
          path: this.renameData.path, // 菜单路径
          mark: this.renameData.mark, // 备注
          seqno: this.renameData.seqno, // 排序
          createdBy: this.renameData.createdBy, // 创建人
          createdDt: this.renameData.createdDt, // 创建日期
          updatedBy: this.$storeSave.state.userInfo.username || 'XXX', // 修改人
          updatedDt: getTime.getTime()// 修改日期
        }
        this.$http.post(TMGNDIRMAINTAIN, param).then(res => {
          console.log('修改成功')
          console.log(res)
          if (res.data.code == '200') {
            this.renameData = {}
            this.reNameVal = ''
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
            this.getTree()
          }
        }).catch(err => {
          console.log('修改菜单失败')
          console.log(err)
        })
      },
      remove (node, data) {
        // 4.	删除按钮 在表名称右侧,点击删除 弹出确认信息框 分组删除,需要下面没有表才能删除
        console.log(node)
        const parent = node.parent
        const children = parent.data.children || parent.data
        const index = children.findIndex(d => d.menuId === data.menuId)
        this.activatedId = data.menuId
        if (children[index].children && children[index].children.length > 0) {
          this.$alert('当前分组存在子级，是否确定删除？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.deleteModel(data.menuId)
            }).catch(() => {
              console.log('取消删除')
            })
        } else {
          this.$alert('确定删除当前数据？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.deleteModel(data.menuId)
              // this.$message({
              //   type: 'success',
              //   message: '删除成功!'
              // });
            }).catch(() => {
              console.log('取消')
            })
        }
      },
      closeBox () {
        this.isShowAddModel = false
        this.isShowReNam = false
        this.reNameVal = ''
        this.makedate = {}
        this.renameData = {}
      },
       getTheDefaultShow () {
         debugger
         if (this.menuData.length <= 0) {
             return null
         }
         for (let i = 0; i < this.menuData.length; i++) {
            var tmpResult = this.getTheFirstData(this.menuData[i])
             if (tmpResult != null) {
                 this.defaultShow = tmpResult
                 break
             }
         }
           this.showTable(this.defaultShow)
       },
       getTheFirstData (data) {
         if (data.attr === '2') {
             return data
         }
         if (data.attr === '1' && data.children.length <= 0) {
             return null
         } else {
             var tmp = null
             for (let i = 0; i < data.children.length; i++) {
                 tmp = this.getTheFirstData(data.children[i])
                 if (tmp != null) {
                     break
                 }
             }
             return tmp
         }
       },
       // 菜单鼠标移入事件
       mouseenter (data) {
         this.$set(data, 'show', true)
       },
       // 菜单鼠标离开事件
       mouseleave (data) {
         this.$set(data, 'show', false)
       }
    }
}
</script>

<style  lang="stylus" scoped>
    .group {
        border-right: 2px solid #efefef;
        padding-right: 12px;
        display flex
        flex-direction column
        flex-shrink 0
        overflow auto
        height 100%
        width: 260px;
        margin-right: 10px;
        .tree-btn{
            font-weight bolder
            color gray
        }
        .addBox{
            width: 100%;
            padding:10px 0 ;
            color #FD6616
            background:white;
            font-size:16px ;
            display: flex;
            justify-content: space-between;
            [class^='el-icon-']{
                font-size: 15px;
                font-weight: bolder;
                cursor: pointer;
                &::before{
                    margin-right 10px
                    font-size 16px
                }
            }
         }
        .el-dialog__body {
            padding: 30px
        }

        .selectType{
            // margin-left:15px;
            margin:0 auto;
            width:90%;
        }
        .submitBox{
            width: 100%;
            height: 80px;
            padding: 10px;
        }
        .custom-tree-node {
            flex: 1;
            display: flex;
            align-items: center;
            font-size: 14px;
            padding-right: 8px;

        }
        .addModel{
            width:100%;
            padding-bottom: 5px;
            padding-left:2px;
            background: white;
            z-index: 5;
        }
        .activeBGC{
            color:#F95160;
        }
        .el-tree {
            display: inline-block;
            min-width: 100%;
            overflow-y:auto;
            height: 94.4%;
        }
    }

</style>
